
//Global Vars
var currentPage = 1;
// Page handling functions
function goToPage(page) {
    currentPage = page;
    hideSections();
}

function hideSections() {
    // Rewrite to use getElementsByTagName to hide all sections then just show the current section?
    // Could set the ID in goToPage() and just show in here, reducing the code greatly
        if (currentPage === 1) {
            document.getElementById('quantity_page').setAttribute('style', 'display:none');
            document.getElementById('add_product_page').setAttribute('style', 'display:none');
            document.getElementById('home_page').setAttribute('style', 'display:block');
        }
        else if (currentPage === 2) {
            document.getElementById('home_page').setAttribute('style', 'display:none');
            document.getElementById('add_product_page').setAttribute('style', 'display:none');
            document.getElementById('quantity_page').setAttribute('style', 'display:block');
        }
        else if (currentPage === 3) {
            // If barcode is already in field - hide scan button
            barcodeLength = document.getElementById('add_product_barcode').value;
            if (barcodeLength != "") {
               document.getElementById('add_product_scan').setAttribute('style', 'display:none');
            }
            document.getElementById('home_page').setAttribute('style', 'display:none');
            document.getElementById('quantity_page').setAttribute('style', 'display:none');
            document.getElementById('add_product_page').setAttribute('style', 'display:block');
        }
    }

// Scan object
var app = {
    
    // Init constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // `load`, `deviceready`, `offline`, and `online`.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        document.addEventListener('deviceready', this.hideSections, false);
        document.getElementById('scan').addEventListener('click', this.scan, false);
        document.getElementById('add_product_scan').addEventListener('click', this.scan, false);
    },
    
    hideSections: function() {
        document.getElementById('quantity_page').setAttribute('style', 'display:none');
    },

    onDeviceReady: function() {        
        app.receivedEvent('deviceready');
    },    

    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    },

    scan: function() {
        console.log('scanning'); // Log to console for debugging
        
        var scanner = cordova.require("cordova/plugin/BarcodeScanner");

        scanner.scan( function (result) {
            
            ajaxURL = 'http://penguin.uclan.ac.uk/~cbrown9/stock_checker/php_scripts/checkProductExists.php';
            ajaxURL += '?barcode=' + result.text;
            
            $.ajax({
                url: ajaxURL,
                success: function (data) {
                    if (currentPage != 3) {
                        if (data == "not found") {
                            // If product not found;
                            addNow = confirm("Product not in database - Add now?");
                            if (addNow === true) {
                                // Set barcode in field & direct to add product page
                                document.getElementById("add_product_barcode").value = result.text;
                                goToPage(3);
                            }
                            else {
                                alert("Returning to scan");
                                app.scan;
                            }
                        } // end not found
                        else if (data == "found 1") {
                            // Found 1 record;
                            document.getElementById("product_barcode").value = result.text;
                            goToPage(2);
                        }
                        else if (data == "duplicate found") {
                            alert("Duplicate found! This will create an error report for review by admin");
                        }
                    }
                    else {
                        document.getElementById("add_product_barcode").value = result.text;
                        goToPage(3);
                    }
                }, // end success
                
                error: function (xhr, status, error) {
                    // If an error occured;
                    if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
                }
            });
            
            
           console.log("Scanner result: \n" +
                "text: " + result.text + "\n" +
                "format: " + result.format + "\n" +
                "cancelled: " + result.cancelled + "\n");
        
            console.log(result);
            
            
            
        }, function (error) { 
            console.log("Scanning failed: ", error); 
        } );
    } // end scan
};